package com.auto.learning.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.activity.BookListActivity;
import com.auto.learning.activity.MyMessageActivity;
import com.auto.learning.activity.PlayActivity;
import com.auto.learning.activity.WebActivity;
import com.auto.learning.adapter.CommonAdapter;
import com.auto.learning.adapter.ViewHolder;
import com.auto.learning.bean.BookListModel;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SystemMessageBean;
import com.auto.learning.event.Handle;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CircleImageView;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class SystemMessageFragment extends Fragment {
	private final static int DELETE = 1;
	private final static int DELETE_SUCCESS = 2;
	private PullToRefreshListView listview_remind;
	private int pageIndex = 0;
	private ArrayList<SystemMessageBean> systemMessageList = new ArrayList<SystemMessageBean>();
	private View lvProductFooter,headView;
	private TextView lvProductFooterMore,tv_tip;
	private ProgressBar lvProductFooterProgress;
	private TextView lvBtn_more;
	private LinearLayout lvLinear_more;
	private CommonAdapter<SystemMessageBean> adapter;
	
	private int delId = 0;

	private Handle handle = new Handle(getActivity()) {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				MyUserInfo.getInstance().getUserInfoBean().setNotifyUnread(0);
				ResponeResult result = (ResponeResult) msg.obj;
				ArrayList<SystemMessageBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<SystemMessageBean>>() {}.getType());
				String bottom = "";
				if (pageIndex == 0) {
					systemMessageList.clear();
					systemMessageList.addAll(resultList);
				} else {
					systemMessageList.addAll(resultList);
				}
//				((MyMessageActivity)getActivity()).HiddenSystemNotify();
				showTips();
				if (resultList.size() >= 10) {
					pageIndex ++;
					lvBtn_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
				}else {
					bottom = getResources().getString(R.string.text_no_data);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
					lvProductFooterProgress.setVisibility(View.GONE);
					lvBtn_more.setVisibility(View.GONE);
				}
				if (listview_remind != null) {
					listview_remind.onRefreshComplete();
					listview_remind.setTag(0);
				}
				if (systemMessageList != null && systemMessageList.size() > 0) {
					adapter.notifyDataSetChanged();
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				CommonMethod.makeNotice(getActivity(), msg.obj.toString());
				if (listview_remind != null) {
					listview_remind.onRefreshComplete();
					listview_remind.setTag(0);
				}
				break;
			case DELETE_SUCCESS:
				if (delId > 0) {
					int size = systemMessageList.size();
					for (int i = 0; i < size; i++) {
						if (systemMessageList.get(i).getId() == delId) {
							systemMessageList.remove(i);
							showTips();
							if (adapter != null) {
								adapter.notifyDataSetChanged();
							}
							break;
						}
					}
				}
				break;
			case DELETE:
				final int id = msg.arg1;
				String[] a = {"确定","取消"};
				CommonMethod.showDialog(getActivity(), a, "确定要删除这条通知吗?", new DialogListener() {
					
					@Override
					public void otherButtonClick(Dialog dialog) {
						dialog.dismiss();
					}
					
					@Override
					public void okButtonClick(Dialog dialog) {
						dialog.dismiss();
						deleteMsg(id);
					}
					
					@Override
					public void cancelButtonClick(Dialog dialog) {
						dialog.dismiss();
					}
				});
				break;
			}
		}
	};
	
	private void showTips(){
		if (systemMessageList.size() == 0) {
			lvProductFooter.setVisibility(View.GONE);
			listview_remind.setDivider(new ColorDrawable(Color.GRAY));  
			listview_remind.setDividerHeight(0);
			if (listview_remind.getHeaderViewsCount() == 1) {
				listview_remind.addHeaderView(headView);
			}
		} else {
			listview_remind.removeHeaderView(headView);
			lvProductFooter.setVisibility(View.VISIBLE);
			listview_remind.setDivider(new ColorDrawable(Color.GRAY));  
			listview_remind.setDividerHeight(1);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_remind, null);
		inintView(view);
		return view;
	}

	private void inintView(View view) {
		headView = LayoutInflater.from(getActivity()).inflate(R.layout.remind_head_view, null);
		tv_tip = (TextView) headView.findViewById(R.id.tv_tip);
		tv_tip.setText("目前没有消息通知");
		listview_remind = (PullToRefreshListView) view.findViewById(R.id.listview_remind);
		listview_remind.setDivider(new ColorDrawable(Color.GRAY));  
		listview_remind.setDividerHeight(1);  
		adapter = new CommonAdapter<SystemMessageBean>(getActivity(),systemMessageList,R.layout.item_remind) {

			@Override
			public void convert(ViewHolder viewHolder, final SystemMessageBean item) {
				CircleImageView civ_userface = viewHolder.getView(R.id.civ_userface);
				civ_userface.setImageResource(R.drawable.icon);
				viewHolder.setText(R.id.tv_title, item.getAdminName()+"");
				TextView msg = viewHolder.getView(R.id.tv_msg);
				msg.setText(item.getMsg() +"");
				msg.setMaxLines(1000);
				viewHolder.setText(R.id.tv_createTime, item.getCreateTime() +"");
				viewHolder.setVisible(R.id.ll_bookComment, false);
				viewHolder.setVisible(R.id.tv_reply, false);
				if (item.getIsRead() == 2) {
					viewHolder.setVisible(R.id.v_redpoint, false);
				} else {
					viewHolder.setVisible(R.id.v_redpoint, true);
				}
				viewHolder.setOnClickListener(R.id.tv_delete, new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						handle.obtainMessage(DELETE, item.getId(), 0).sendToTarget();
					}
				});
			}
		};
		listview_remind.setSelector(new ColorDrawable(Color.TRANSPARENT));
		listview_remind.setAdapter(adapter);
		listview_remind.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (systemMessageList.size() == 0) {
					return;
				}
				SystemMessageBean systemMessageBean = systemMessageList.get(position - 1);
				Intent mIntent = null;
				if (systemMessageBean.getH5() != null) {
					mIntent = new Intent(getActivity(), WebActivity.class);
					mIntent.putExtra("url", systemMessageBean.getH5().getH5().replace("{userId}", String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
					mIntent.putExtra("showtitle", true);
					mIntent.putExtra("title",systemMessageBean.getH5().getName()+"");
					mIntent.putExtra("h5_model", systemMessageBean.getH5());
				} else {
					switch (systemMessageBean.getNotifyType()) {
					case 2:
						int bookId = systemMessageBean.getBookId();
						String faceImg ;
						if (systemMessageBean.getBookInfo() != null) {
							faceImg = systemMessageBean.getBookInfo().getFaceImg();
						}else {
							return;
						}
						TemporaryVariable.read_list.clear();
						TemporaryVariable.read_list.add(bookId);
						if (TemporaryVariable.playActivity != null && TemporaryVariable.playActivity instanceof PlayActivity) {
							TemporaryVariable.playActivity.finish();
						}
						mIntent = new Intent(getActivity(), PlayActivity.class);
						mIntent.putExtra("bookId", bookId);
						mIntent.putExtra("canRead", systemMessageBean.getBookInfo().getCanRead());
						mIntent.putExtra("needBuy", systemMessageBean.getBookInfo().getNeedBuy());
						mIntent.putExtra("faceImg", faceImg);
						mIntent.putExtra("type", 1);
						break;
					case 3:
						int listId = systemMessageBean.getBooklistId();
						mIntent = new Intent(getActivity(), BookListActivity.class);
						BookListModel bookListModel = null;
						if (systemMessageBean.getBooklistInfo() != null) {
							bookListModel = systemMessageBean.getBooklistInfo();
						}else {
							bookListModel = new BookListModel();
							bookListModel.setListId(listId);
						}
				    	mIntent.putExtra("data", bookListModel);
						break;
					}
				}
				
				if (mIntent != null) {
					startActivity(mIntent);
				}
			}
		});
		lvProductFooter = getActivity().getLayoutInflater().inflate(R.layout.listview_footer, null);
		lvProductFooterMore = (TextView) lvProductFooter.findViewById(R.id.listview_foot_more);
		lvProductFooterProgress = (ProgressBar) lvProductFooter.findViewById(R.id.listview_foot_progress);
		lvBtn_more = (TextView) lvProductFooter.findViewById(R.id.btn_more);
		lvLinear_more = (LinearLayout) lvProductFooter.findViewById(R.id.linear_more);
		lvProductFooter.setBackgroundColor(getActivity().getResources().getColor(R.color.white));
		listview_remind.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				pageIndex = 0;
				getData();
			}
		});
		
		listview_remind.addFooterView(lvProductFooter);
		lvBtn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getData();
			}
		});
		listview_remind.setTag("0");
		listview_remind.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				listview_remind.onScrollStateChanged(view, scrollState);
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvProductFooter) == view.getLastVisiblePosition()
							&& !lvProductFooterMore.getText().toString().equals(getResources().getString(R.string.text_no_data))) {
						scrollEnd = true;
					}
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				int lvDataState = Integer.parseInt((listview_remind.getTag().toString()));
				if (scrollEnd && lvDataState == 0) {
					listview_remind.setTag(1);
					lvProductFooterMore.setText("加载中");
					lvProductFooterProgress.setVisibility(View.VISIBLE);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvBtn_more.setVisibility(View.GONE);
					int page = listview_remind.getCount() - 2;   
					getData();
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				listview_remind.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		listview_remind.clickRefresh();
	}

	public void getData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String.valueOf(pageIndex)));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.NOTIFY_LIST, params, handle, HttpRequestHelper.GETDATA_SUCCESS,HttpRequestHelper.GETDATA_FAIL);
	}
	
	public void deleteMsg(int id){
		delId = id;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("idList", String.valueOf(id)));
		HttpRequestHelper.executeHttpDataNoData(getActivity(),HttpRequestHelper.NOTIFY_DEL,params,handle,DELETE_SUCCESS, HttpRequestHelper.GETDATA_FAIL);
	}

}
